package com.mm.cloth.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.PorterDuffColorFilter;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import android.util.Log;

public class MaskDrawingView extends View {
    private static final String TAG = "MaskDrawingView";
    
    private Paint drawPaint;
    private Paint canvasPaint;
    private Path drawPath;
    private Canvas drawCanvas;
    private Bitmap canvasBitmap;
    private Bitmap originalBitmap;
    private Bitmap maskBitmap;
    
    private boolean hasMaskDrawn = false;
    private float brushSize = 20f;

    // 撤销重做功能
    private List<Bitmap> undoStack = new ArrayList<>();
    private List<Bitmap> redoStack = new ArrayList<>();
    private static final int MAX_UNDO_STEPS = 10;
    
    public MaskDrawingView(Context context) {
        super(context);
        setupDrawing();
    }
    
    public MaskDrawingView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setupDrawing();
    }
    
    public MaskDrawingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setupDrawing();
    }
    
    private void setupDrawing() {
        drawPath = new Path();
        drawPaint = new Paint();

        drawPaint.setColor(Color.BLACK); // 改为黑色遮罩
        drawPaint.setAntiAlias(true);
        drawPaint.setStrokeWidth(brushSize);
        drawPaint.setStyle(Paint.Style.STROKE);
        drawPaint.setStrokeJoin(Paint.Join.ROUND);
        drawPaint.setStrokeCap(Paint.Cap.ROUND);
        drawPaint.setAlpha(180); // 增加不透明度，黑色更明显

        canvasPaint = new Paint(Paint.DITHER_FLAG);
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        
        if (w > 0 && h > 0) {
            canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            drawCanvas = new Canvas(canvasBitmap);
            drawCanvas.drawColor(Color.TRANSPARENT);
        }
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int viewWidth = getWidth();
        int viewHeight = getHeight();

        // 绘制原图（居中显示）
        if (originalBitmap != null) {
            float offsetX = (viewWidth - originalBitmap.getWidth()) / 2f;
            float offsetY = (viewHeight - originalBitmap.getHeight()) / 2f;
            canvas.drawBitmap(originalBitmap, offsetX, offsetY, canvasPaint);
        }

        // 绘制上传的遮罩（居中显示）
        if (maskBitmap != null) {
            Paint maskPaint = new Paint();
            maskPaint.setAlpha(180);
            maskPaint.setColorFilter(new PorterDuffColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP));

            float offsetX = (viewWidth - maskBitmap.getWidth()) / 2f;
            float offsetY = (viewHeight - maskBitmap.getHeight()) / 2f;
            canvas.drawBitmap(maskBitmap, offsetX, offsetY, maskPaint);
        }

        // 绘制手绘遮罩
        if (canvasBitmap != null) {
            canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
        }

        // 绘制当前路径
        canvas.drawPath(drawPath, drawPaint);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (originalBitmap == null) {
            return false;
        }

        float touchX = event.getX();
        float touchY = event.getY();

        // 检查触摸点是否在图片区域内
        int viewWidth = getWidth();
        int viewHeight = getHeight();
        float offsetX = (viewWidth - originalBitmap.getWidth()) / 2f;
        float offsetY = (viewHeight - originalBitmap.getHeight()) / 2f;

        // 只在图片区域内响应触摸
        if (touchX >= offsetX && touchX <= offsetX + originalBitmap.getWidth() &&
            touchY >= offsetY && touchY <= offsetY + originalBitmap.getHeight()) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 在开始绘制前保存当前状态
                    saveToUndoStack();
                    drawPath.moveTo(touchX, touchY);
                    break;

                case MotionEvent.ACTION_MOVE:
                    drawPath.lineTo(touchX, touchY);
                    break;

                case MotionEvent.ACTION_UP:
                    if (drawCanvas != null) {
                        drawCanvas.drawPath(drawPath, drawPaint);
                    }
                    drawPath.reset();
                    hasMaskDrawn = true;
                    break;

                default:
                    return false;
            }

            invalidate();
            return true;
        }

        return false;
    }
    
    public void setOriginalBitmap(Bitmap bitmap) {
        // 延迟缩放，等待View尺寸确定
        post(() -> {
            this.originalBitmap = scaleBitmapToView(bitmap);

            // 重新创建画布
            if (getWidth() > 0 && getHeight() > 0) {
                canvasBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
                drawCanvas = new Canvas(canvasBitmap);
                drawCanvas.drawColor(Color.TRANSPARENT);
            }

            hasMaskDrawn = false;
            invalidate();
        });
    }

    public void setMaskBitmap(Bitmap bitmap) {
        // 延迟缩放，等待View尺寸确定
        post(() -> {
            this.maskBitmap = scaleBitmapToView(bitmap);
            invalidate();
        });
    }
    
    private Bitmap scaleBitmapToView(Bitmap bitmap) {
        if (bitmap == null || getWidth() == 0 || getHeight() == 0) {
            return bitmap;
        }

        int viewWidth = getWidth();
        int viewHeight = getHeight();
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();

        // 使用centerInside模式，保持宽高比并完全显示在View内
        float scaleX = (float) viewWidth / bitmapWidth;
        float scaleY = (float) viewHeight / bitmapHeight;
        float scale = Math.min(scaleX, scaleY);

        int scaledWidth = (int) (bitmapWidth * scale);
        int scaledHeight = (int) (bitmapHeight * scale);

        return Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
    }
    
    public boolean hasMask() {
        return hasMaskDrawn || maskBitmap != null;
    }
    

    
    public void setBrushSize(float size) {
        this.brushSize = size;
        drawPaint.setStrokeWidth(size);
    }
    
    public Bitmap getMaskBitmap() {
        if (canvasBitmap != null) {
            return canvasBitmap.copy(Bitmap.Config.ARGB_8888, false);
        }
        return null;
    }

    // 撤销重做功能
    private void saveToUndoStack() {
        if (canvasBitmap != null) {
            try {
                // 保存当前状态到撤销栈
                Bitmap currentState = canvasBitmap.copy(Bitmap.Config.ARGB_8888, false);
                undoStack.add(currentState);

                // 限制撤销栈大小
                if (undoStack.size() > MAX_UNDO_STEPS) {
                    Bitmap oldBitmap = undoStack.remove(0);
                    if (oldBitmap != null && !oldBitmap.isRecycled()) {
                        oldBitmap.recycle();
                    }
                }

                // 清空重做栈
                for (Bitmap bitmap : redoStack) {
                    if (bitmap != null && !bitmap.isRecycled()) {
                        bitmap.recycle();
                    }
                }
                redoStack.clear();
            } catch (Exception e) {
                Log.e("MaskDrawingView", "保存撤销状态失败: " + e.getMessage());
            }
        }
    }

    public void undo() {
        if (!undoStack.isEmpty()) {
            try {
                // 保存当前状态到重做栈
                if (canvasBitmap != null) {
                    Bitmap currentState = canvasBitmap.copy(Bitmap.Config.ARGB_8888, false);
                    redoStack.add(currentState);
                }

                // 恢复上一个状态
                Bitmap previousState = undoStack.remove(undoStack.size() - 1);
                if (canvasBitmap != null && drawCanvas != null && previousState != null) {
                    drawCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                    drawCanvas.drawBitmap(previousState, 0, 0, canvasPaint);
                }

                hasMaskDrawn = !undoStack.isEmpty() || (canvasBitmap != null);
                invalidate();
            } catch (Exception e) {
                Log.e("MaskDrawingView", "撤销操作失败: " + e.getMessage());
            }
        }
    }

    public void redo() {
        if (!redoStack.isEmpty()) {
            try {
                // 保存当前状态到撤销栈（不清空重做栈）
                if (canvasBitmap != null) {
                    Bitmap currentState = canvasBitmap.copy(Bitmap.Config.ARGB_8888, false);
                    undoStack.add(currentState);

                    // 限制撤销栈大小
                    if (undoStack.size() > MAX_UNDO_STEPS) {
                        Bitmap oldBitmap = undoStack.remove(0);
                        if (oldBitmap != null && !oldBitmap.isRecycled()) {
                            oldBitmap.recycle();
                        }
                    }
                }

                // 恢复重做状态
                Bitmap redoState = redoStack.remove(redoStack.size() - 1);
                if (canvasBitmap != null && drawCanvas != null && redoState != null) {
                    drawCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                    drawCanvas.drawBitmap(redoState, 0, 0, canvasPaint);
                }

                hasMaskDrawn = true;
                invalidate();
            } catch (Exception e) {
                Log.e("MaskDrawingView", "重做操作失败: " + e.getMessage());
            }
        }
    }

    public void clearMask() {
        saveToUndoStack(); // 保存清除前的状态

        if (canvasBitmap != null) {
            drawCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        }
        maskBitmap = null;
        hasMaskDrawn = false;
        invalidate();
    }
}
